﻿using Senparc.Weixin.MP.AdvancedAPIs;
using Senparc.Weixin.MP.AdvancedAPIs.TemplateMessage;
using Senparc.Weixin.MP.Containers;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Weixin.Core.config;
using Weixin.Core.Model;

namespace Weixin.Core
{
    /// <summary>
    /// 微信模版消息
    /// </summary>
    public class TemplateMessageHelp
    {

        #region singleton
        private static TemplateMessageHelp instance;
        //private static object _lock = new object();
        private TemplateMessageHelp()
        {

        }

        public static TemplateMessageHelp GetInstance()
        {
            if (instance == null)
            {
                instance = new TemplateMessageHelp();
            }
            return instance;
        }
        #endregion

        /// <summary>
        /// 商品消费模版
        /// </summary>
        /// <param name="template"></param>
        /// <param name="openId"></param>
        /// <returns></returns>
        public string CommodityOrderTemplateMessage(ProductTemplate template,string openId)
        {

            //根据appId判断获取    
            if (!AccessTokenContainer.CheckRegistered(WxConfig.AppId))    //检查是否已经注册    
            {
                AccessTokenContainer.Register(WxConfig.AppId, WxConfig.AppSecret);    //如果没有注册则进行注册    
            }

            string access_token = AccessTokenContainer.GetAccessTokenResult(WxConfig.AppId).access_token; //AccessToken  
            string templateId = "5vVhdvFr_-5vVSmwY6aw5VLMRDBjZinu0hX9XK-1LOo";   //模版id  
            string linkUrl = "http://www.baidu.com";    //点击详情后跳转后的链接地址，为空则不跳转 

            //为模版中的各属性赋值  
            var templateData = new ProductTemplateData()
            {
                first = new TemplateDataItem(template.first, "#000000"),
                orderProductPrice = new TemplateDataItem(template.orderProductPrice, "#000000"),
                orderProductName = new TemplateDataItem(template.orderProductName, "#000000"),
                orderAddress = new TemplateDataItem(template.orderAddress, "#000000"),
                orderName= new TemplateDataItem(template.orderName, "#000000"),
                remark = new TemplateDataItem(template.remark, "#000000")
            };

            SendTemplateMessageResult sendResult = TemplateApi.SendTemplateMessage(access_token,openId,templateId,linkUrl, templateData);

            return sendResult.errcode.ToString();
        }
    }
}
